package com.midian.common.interceptor;

import java.lang.reflect.Method;

import com.midian.action.mc.common.AjaxAction;
import com.midian.model.common.BaseModel;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 * 链式对象构造拦截器
 * @author Savage.M
 *
 */
public class ChainObjConstructInterceptor extends MethodFilterInterceptor {
	
	/**
	 * 处理子对象（检查id值）
	 * @param entity 实体对象
	 * @throws Exception
	 */
	private void opSubEntity(Object entity) throws Exception {
		if(entity != null) {
			Method[] methods = entity.getClass().getMethods();
			for (Method method : methods) {
				//获取BaseModel子类对象类型的get方法
				if(method.getName().startsWith("get") && BaseModel.class.isAssignableFrom(method.getReturnType())) {
					Object subEntity = method.invoke(entity);
					if(subEntity != null) {
						Method getIdMethod = subEntity.getClass().getMethod("getId");
						//获取id值
						String id = String.valueOf(getIdMethod.invoke(subEntity)).trim();
						//如果id值为空，置空对象
						if("".equals(id)) {
							//获取entity的set方法名称
							String setEntityMethodName = "set" + method.getName().substring(3);
							//获取entity的set方法
							Method setEntityMethod = entity.getClass().getMethod(setEntityMethodName, method.getReturnType());
							setEntityMethod.invoke(entity, new Object[]{null});
							return;
						} else {
						//如果id值不为空，继续进行子对象的检查
							opSubEntity(subEntity);
						}
					}
				}
			}
		}
	}
	
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		//获取目标Action对象
		Object action = invocation.getAction();
		if(action instanceof AjaxAction) {
			Method entityGetMethod = action.getClass().getMethod("getEntity");
			Object entity = entityGetMethod.invoke(action); //entity对象的值
			//处理子对象（检查id值）
			opSubEntity(entity);
		}
		return invocation.invoke();
	}
}
